<script setup lang="ts">

import {message} from "ant-design-vue";
import {getCurrentInstance} from "vue";
import BaseApp from "~/contentScripts/views/sycm/baseApp.vue";
import User from "~/contentScripts/views/tao/list/components/user.vue";
import {isLogin} from "~/logic";
import SYCM from "~/utils/ali/sycm";
import Trans from "~/utils/sycm/trans";

let pix = inject('selectorPix');
const loginVisible = ref(false);
const appendChangeBox = (dom: Element, index: string, value: number) => {
  let _dom = dom.querySelector('.xc-change-box');
  if (_dom) {
    _dom.remove();
  }
  _dom = document.createElement('span');
  _dom.style.color = 'green';
  _dom.style.fontSize = '12px';
  _dom.className = 'xc-change-box';
  if (SYCM.toNumberIndex.includes(index)) {
    if (isNaN(value)) {
      _dom.innerHTML = `(0)`;
    } else if (isNaN(Trans.number(value))) {
      _dom.innerHTML = `(0)`;
    } else {
      _dom.innerHTML = `(${formatNumber(Trans.number(value))})`;
    }
    dom.append(_dom);
    calcNumber.value++;
  } else if (SYCM.ToRatioIndex.includes(index)) {
    if (isNaN(value)) {
      _dom.innerHTML = `(0%)`;
    } else {
      _dom.innerHTML = `(${Trans.ratio(value)})`;
    }
    dom.append(_dom);
    calcNumber.value++;
  } else {
    // console.log(dom, index, value);
  }
}
const calcNumber = ref<number>(0);
const indexes = ref<string[]>([]);

const __option = getCurrentInstance()?.appContext.provides.option;
const handle = async () => {
  if (isLogin({
    emit: () => {
      loginVisible.value = true;
    }
  }, __option)) {
    calcNumber.value = 0;
    // 单选的
    const currActiveElement = document.querySelector(pix + ' .oui-index-picker-item input[type=radio]:checked');
    if (currActiveElement) {
      const index = currActiveElement.getAttribute('value');
      if (index) {
        const rows = document.querySelectorAll(pix + ' .ant-table-row');
        rows.forEach((el) => {
          let doms = el.querySelectorAll('p');
          doms.forEach((dom) => {
            appendChangeBox(dom, index, parseInt(dom.innerHTML.replaceAll(/<[^>]+>/g, '').replaceAll(',', '').replaceAll(' ', '')));
          });
        })
      }
    }
    // 市场-搜索人群-属性画像 指数转换
    let searchCustomerDoms = document.querySelectorAll(pix + ' .index-value');
    console.log(pix + ' .index-value',searchCustomerDoms);
    searchCustomerDoms.forEach((dom)=>{
      let value = dom.innerHTML.replaceAll(/<[^>]+>/g, '').replaceAll(',', '').replaceAll(' ', '');
      // 不存在%
      if (value.indexOf('%') === -1) {
        if (document.querySelector(pix)?.innerHTML.includes('支付转化指数')){
          appendChangeBox(dom, 'payRateIndex', parseInt(value));
        }else {
          appendChangeBox(dom, 'tradeIndex', parseInt(value));
        }
      }
    })

    // 市场-搜索人群-属性画像-表格 指数转换
    let searchCustomerTableDoms = document.querySelectorAll(pix + ' .value-td-value');
    // console.log(pix + ' .index-value',searchCustomerDoms);
    searchCustomerTableDoms.forEach((dom)=>{
      let value = dom.innerHTML.replaceAll(/<[^>]+>/g, '').replaceAll(',', '').replaceAll(' ', '');
      // 不存在%
      if (value.indexOf('%') === -1) {
        if (document.querySelector(pix)?.innerHTML.includes('支付转化指数')){
          console.log('支付转化指数',value)
          appendChangeBox(dom, 'payRateIndex', parseInt(value));
        }else {
          appendChangeBox(dom, 'tradeIndex', parseInt(value));
        }
      }
    })

    // 市场 搜索分析-类目构成 上面的自定义tab
    let doms = document.querySelectorAll('[id^=__qiankun_microapp_wrapper_for_op_mc] > div > div > div > div > div.oui-card > div.oui-card-content > span > div.oui-tab-switch-item-custom > table > tbody > tr:nth-child(1) > td:nth-child(2)');
    doms.forEach((dom) => {
      appendChangeBox(dom, 'clickHits', parseInt(dom.innerHTML.replaceAll(/<[^>]+>/g, '').replaceAll(',', '').replaceAll(' ', '')));
    })
    // 多选的
    indexes.value = [];
    document.querySelectorAll(pix + ' .oui-index-picker-item input.ant-checkbox-input').forEach((e, i) => {
      if (e.checked) {
        let index = e.value;
        if (index) {
          indexes.value.push(index);
        }
      }
    });
    if (indexes.value.length) {
      document.querySelectorAll(pix + ' tr.ant-table-row').forEach((tr) => {
        tr.querySelectorAll('.ant-table-column-has-filters .shop-list-tbl-td').forEach((td, index) => {
          let value = td.innerHTML;
          let _value = parseInt(value.replaceAll(/<[^>]+>/g, '').replaceAll(',', '').replaceAll(' ', ''));
          if (!isNaN(_value)) {
            appendChangeBox(td, indexes.value[index], parseInt(value.replaceAll(/<[^>]+>/g, '').replaceAll(',', '').replaceAll(' ', '')));
          }
        })
      });
    }
    // 竞品分析竞店分析处理
    let arrow = document.querySelector(pix + " .alife-one-design-sycm-indexes-trend-index-page-arrow-container");
    if (arrow) {
      arrow.onclick = () => {
        document.querySelectorAll(pix + ' .xc-change-box').forEach(e => e.remove());
      }
    }
    indexes.value = [];
    document.querySelectorAll(pix + ' [class^=alife-one-design-sycm-indexes-trend-index-item-]').forEach((d, i) => {
      let index = '';
      d.className.split(' ').forEach(e => {
        if (e.indexOf('alife-one-design-sycm-indexes-trend-index-item-') > -1) {
          index = e.replace('alife-one-design-sycm-indexes-trend-index-item-', '');
        }
      })
      indexes.value.push(index);
      let doms = d.querySelectorAll('.oui-num');
      doms.forEach((e) => {
        let value = e.innerHTML;
        let _value = parseInt(value.replaceAll(/<[^>]+>/g, '').replaceAll(',', '').replaceAll(' ', ''));
        if (!isNaN(_value)) {
          appendChangeBox(e, index, parseInt(value.replaceAll(/<[^>]+>/g, '').replaceAll(',', '').replaceAll(' ', '')));
        }
      })
    });

    // 普通table带index处理
    let _index = SYCM.toNumberIndex;
    let selector = _index.map(e => pix + ' .alife-dt-card-common-table-' + e).join(',');
    let _data: any = document.querySelectorAll(selector);
    if (_data === null) {
      // message.error('获取数据失败，请刷新后重试！');
      return;
    }
    for (let i = 0; i < _data.length; i++) {
      // if (i > 0) {
      let child = _data[i].querySelector('.alife-dt-card-common-table-sortable-value span,.alife-dt-card-common-table-ordered-value span');
      if (child) {
        let _value = child.innerHTML.replaceAll(',', '');
        let box = _data[i].querySelector('.xc-change-box');
        if (!box) {
          box = document.createElement('span');
        }
        let value = Trans.number(_value);
        if (isNaN(value)) {
          box.innerHTML = '(0)';
        } else {
          box.innerHTML = '(' + formatNumber(value) + ')';
        }
        box.className = 'xc-change-box'
        box.style.color = 'green';
        // span.style.fontSize = '12px';
        box.style.paddingTop = '10px';
        _data[i].querySelector('.alife-dt-card-common-table-sortable-value,.alife-dt-card-common-table-ordered-value').append(box);
        calcNumber.value++;
      }
      // }
    }
    _index = SYCM.ToRatioIndex;
    selector = _index.map(e => pix + ' .alife-dt-card-common-table-' + e).join(',');
    _data = document.querySelectorAll(selector);
    if (_data === null) {
      // message.error('获取数据失败，请刷新后重试！');
      return;
    }
    for (let i = 0; i < _data.length; i++) {
      // if (i > 0) {
      let child = _data[i].querySelector('.alife-dt-card-common-table-sortable-value span,.alife-dt-card-common-table-ordered-value span');
      if (child) {
        let _value = child.innerHTML.replaceAll(',', '');
        let box = _data[i].querySelector('.xc-change-box');
        if (!box) {
          box = document.createElement('span');
        }
        let value = Trans.ratio(_value);
        if (isNaN(value)) {
          box.innerHTML = '(0)';
        } else {
          box.innerHTML = '(' + formatNumber(value) + ')';
        }
        box.className = 'xc-change-box'
        box.style.color = 'green';
        // span.style.fontSize = '12px';
        box.style.paddingTop = '10px';
        _data[i].querySelector('.alife-dt-card-common-table-sortable-value,.alife-dt-card-common-table-ordered-value').append(box);

        calcNumber.value++;
      }
      // }
    }

    //客群透视分析
    if (document.querySelector('#customerAnalysis .card-sycm-heatmap-table')) {
      let doms = document.querySelectorAll('#customerAnalysis .card-sycm-heatmap-table .cell>div');
      doms.forEach((e) => {
        let value = e.innerHTML;
        let _value = parseInt(value.replaceAll(/<[^>]+>/g, '').replaceAll(',', '').replaceAll(' ', ''));
        if (!isNaN(_value) && e.innerHTML.indexOf('%') === -1) {
          appendChangeBox(e, 'tradeIndex', parseInt(value.replaceAll(/<[^>]+>/g, '').replaceAll(',', '').replaceAll(' ', '')));
        }
      })
    }

    if (!calcNumber.value) {
      message.warning('没有需要计算的指数哦~');
    }
  }
};

const formatNumber = (value: number) => {
  return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
</script>

<template>
  <base-app>
    <a-button-group>
      <user @login="loginVisible=true" :style="{
        marginRight: '0'
      }"
      />
      <!--      <a-button type="primary" size="small" @click="handle2">指数换算</a-button>-->
      <a-button type="primary" size="small" @click="handle">指数换算</a-button>
    </a-button-group>
    <user-login-modal v-model:visible="loginVisible" @close="loginVisible=false"/>
  </base-app>
</template>

<style scoped>

</style>
